
/*
 * GET users listing.
 */

var models = require('./models');

var users = models.users;

//手机客户端登陆
exports.doLogin = function(req,res){
    var query = {un : req.body.username,pw : req.body.password};
    users.count(query,function(err,doc){
        if (doc == 1) {
            res.send("1");
        }else{
            res.send("0");
        };
    });
};

exports.list = function (req, res) {
    res.render('main',{un : req.user.em});
    //var html = "<h2>你好, " + req.user.em + "</h2><a href='/logout'>退出</a>";
    //res.send(html);
};

exports.getUserAll = function(req,res){
    if(req.user.un=='admin'){
        users.find({},function(err,docs){
            res.render('user_list',{users : docs});
        });
    }else{
       res.send('你没有权限执行该操作！');
    }
};
exports.addUserUi = function(req,res){
    res.render('add_user');
};
exports.addUser = function(req,res){
    var newUser =  new users();
    newUser.un = req.body.username;
    newUser.pw = req.body.password;
    newUser.em = req.body.employ;
    newUser.save(function(err){
        if(err){
            res.send('{"statusCode":"300","message":"操作失败,该用户名已经存在！"}');
        }else{
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"userList","forwardUrl":"showUsersPost", "callbackType":"closeCurrent"}');
        }
    });
};
exports.deleteUserOne = function(req,res){
    var uId = req.param('uid');
    users.remove({_id : uId},function(err){
        if (err) {
            res.send('{"statusCode":"300","message":"操作失败!"}');
        }else{
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"userList","forwardUrl":"showUsersPost"}');
        };
    });
};
exports.updateUserOneUi = function(req,res){
    var uid = req.param('uid');
    users.findById(uid,function(err,doc){
        res.render('update_user',{user : doc});
    })
};
exports.updateUser = function(req,res){
    var uid = req.body.uid;
    users.update({_id : uid},{$set : {pw : req.body.password,em : req.body.employ}},function(err){
        if (err) {
            res.send('{"statusCode":"300","message":"操作失败!"}');
        }else{
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"userList","forwardUrl":"showUsersPost","callbackType":"closeCurrent"}');
        };
    });
};
exports.updatePwUI = function(req,res){
    res.render('set_password',{un:req.user.un});
};
exports.updatePw = function(req,res){
    var username = req.body.un;
    var oldPw = req.body.oldpw;
    var newPw = req.body.surepw;
    users.findOne({un:username},function(err,doc){
        if(doc.pw != oldPw){
            res.send('{"statusCode":"300","message":"旧密码输入错误!"}');
        }else{
            doc.pw = newPw;
            doc.save();
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"","forwardUrl":"","callbackType":"closeCurrent"}');
        }
    });
};